package com.example.finalproject;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.splashscreen.SplashScreen;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;

import com.example.finalproject.adapter.ViewPagerAdapter;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

public class MainActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    private ViewPagerAdapter viewPagerAdapter;

    private boolean isSplashVisible = true;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // 安装 SplashScreen
        SplashScreen splashScreen = SplashScreen.installSplashScreen(this);
        // 保持 Splash 屏幕 3 秒
        splashScreen.setKeepOnScreenCondition(() -> isSplashVisible);
        // 3秒后关闭 Splash
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            isSplashVisible = false;
        }, 3000);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setInitView();

        int targetIndex = getIntent().getIntExtra("navigate_to_index", -1);
        if (targetIndex >= 0 && targetIndex < viewPagerAdapter.getItemCount()) {
            viewPager2.setCurrentItem(targetIndex, false);
        }
    }

    private void setInitView() {
        tabLayout = findViewById(R.id.tabLayout);
        viewPager2 = findViewById(R.id.viewPager);
        viewPagerAdapter = new ViewPagerAdapter(this);
        viewPager2.setAdapter(viewPagerAdapter);

        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2, true, (tab, position) -> {
            if (viewPagerAdapter != null) {
                tab.setText(viewPagerAdapter.getItemTitle(position));
            }
        });
        tabLayoutMediator.attach();
    }
}